package cn.xiuxius.embedded.comdev;

import com.fazecast.jSerialComm.SerialPort;
import lombok.Getter;

public class SerialPortManager {
    @Getter
    private final SerialPort port;
    private boolean isRunning;


    public SerialPortManager(SerialPort port) {
        this.port = port;
    }

    public boolean openPort() {
        isRunning = port.openPort();
        return isRunning;
    }

    public void sendData(String data) {
        if (isRunning) {
            int written = port.writeBytes(data.getBytes(), data.length());
            if (written <= 0) {
                port.closePort();
            }
        }
    }

    public void sendHex(byte[] data) {
        if (isRunning) {
            port.writeBytes(data, data.length);
        }
    }

    public void addDataListener(SerialPortDataListenerImpl listener) {
        port.addDataListener(listener);
    }

    public void closePort() {
        if (port != null && port.isOpen())  {
            port.closePort();
            isRunning = false;
        }
    }

}